home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2000 January / maximum-cd-2000-01.iso / Dreamweaver2 / data1.cab / Program_Files / Configuration / Behaviors / Actions / Validate Form.js < prev   
Encoding:
JavaScript  |  1999-02-23  |  12.3 KB  |  321 lines

  1. // Copyright 1998 Macromedia, Inc. All rights reserved.
  2.  
  3. //*************** GLOBAL VARS  *****************
  4.  
  5. //******************* BEHAVIOR FUNCTION **********************
  6.  
  7. //Validates a form by checking the values in multiple text fields.
  8. //Accepts a variable number of args, in pairs as follows:
  9. //  objStrNS - Javascript text object ref for Netscape (ex: document.myForm.Email)
  10. //  objStrIE - JScript text object ref for Internet Explorer (ex: document.all['Email'])
  11. //  theCheck - what to check: [R|N][isEmail|isNum|inRange<fromNum>:<toNum>], where:
  12. //                R       - some value is Required (non-empty)
  13. //                N       - value is Not required
  14. //                isEmail - value must have an @ with at least 1 char before & after (x@y)
  15. //                isNum   - value must be a number
  16. //                inRange - value is between the two numbers, inclusive
  17. //             Examples:
  18. //               user must enter *something*:     R
  19. //               a required Email field:          RisEmail
  20. //               an optional Age field:           NisNum
  21. //               a required # of orders, max 100: RinRange1:100
  22. //
  23. //Tests for browser, and uses the first object string for NS, the second for IE.
  24. //Fixes the form reference if its in a layer and layers aren't supported (older browsers).
  25. //Gets the value from the text input or text area and runs the check as follows:
  26. //  if the field is not empty
  27. //    if theCheck is "isEmail", ensure we have at least x@y, else give error
  28. //    else if theCheck isn't just "R", all that's left is isNum or inRange
  29. //      if field is not a number give error
  30. //      else if field not in range give error
  31. //  else if theCheck is "R" give error
  32. //Batches up all error values and returns them in a single alert() dialog.
  33. //Also, sets the global return value to false. If this Action is paired with the onSubmit
  34. //message, it can prevent the form from submitting if there are errors.
  35.  
  36. function MM_validateForm() { //v2.0
  37.   var i,objStr,field,theCheck,atPos,theNum,colonPos,min,max,errors='';
  38.   for (i=0; i<(MM_validateForm.arguments.length-2); i+=3) {
  39.     objStr = MM_validateForm.arguments[(navigator.appName == 'Netscape')?i:i+1];
  40.     if ((objStr.indexOf('document.layers[')==0 && document.layers==null) ||
  41.         (objStr.indexOf('document.all[')   ==0 && document.all   ==null))
  42.       objStr = 'document'+objStr.substring(objStr.substring(0,objStr.lastIndexOf('.')).
  43.                  lastIndexOf('.'),objStr.length);  //fix layer ref if not supp
  44.     field = eval(objStr);
  45.     field.name = (field.name)?field.name:objStr;
  46.     theCheck = MM_validateForm.arguments[i+2];
  47.     if (field.value) { //IF NOT EMPTY FIELD
  48.       if (theCheck.indexOf('isEmail') != -1) { //CHECK EMAIL
  49.         atPos = field.value.indexOf('@');
  50.         if (atPos < 1 || atPos == (field.value.length - 1))
  51.           errors += '- '+field.name+' must contain an e-mail address.\n';
  52.       } else if (theCheck != 'R') { //START NUM CHECKS
  53.         theNum = parseFloat(field.value);
  54.         if (field.value != ''+theNum) errors += '- '+field.name+' must contain a number.\n';
  55.         if (theCheck.indexOf('inRange') != -1) { //CHECK RANGE
  56.           colonPos = theCheck.indexOf(':');
  57.           min = theCheck.substring(8,colonPos);
  58.           max = theCheck.substring(colonPos+1,theCheck.length);
  59.           if (theNum < min || max < theNum) //bad range
  60.             errors += '- '+field.name+' must contain a number between '+min+' and '+max+'.\n';
  61.     } } }
  62.     else if (theCheck.charAt(0) == 'R') errors += '- '+field.name+' is required.\n';
  63.   }
  64.   if (errors) alert('The following error(s) occurred:\n'+
  65.                     errors);
  66.   document.MM_returnValue = (errors == '')
  67. }
  68.  
  69.  
  70. //******************* API **********************
  71.  
  72.  
  73. //Checks for the existence of text fields.
  74. //If none exist, returns false so this Action is grayed out.
  75.  
  76. function canAcceptBehavior(tagStr,eventStr){
  77.   var nameArray = getAllObjectRefs("NS 4.0","INPUT/TEXT","TEXTAREA","INPUT/PASSWORD");
  78.   return (nameArray.length > 0);
  79. }
  80.  
  81.  
  82.  
  83. //Returns a Javascript function to be inserted in HTML head with script tags.
  84.  
  85. function behaviorFunction(){
  86.   return "MM_validateForm";
  87. }
  88.  
  89.  
  90.  
  91. //Returns fn call to insert in HTML tag <TAG... onEvent='thisFn(arg)'>
  92.  
  93. function applyBehavior() {
  94.   var curFormNum,menuLength,i,chkStr,fieldName,firstArg,secondArg,retArgs = "";
  95.  
  96.   //scan fieldMenu for values
  97.   menuLength = document.theForm.fieldMenu.options.length;
  98.   for (i=0; i<menuLength; i++) {
  99.     chkStr = getMenuValue(eval(i));
  100.     if (chkStr) {
  101.       //found a value, package up the string
  102.       fieldName = document.MM_NS_REFS[i];
  103.  
  104.       if (fieldName.indexOf(REF_UNNAMED) == 0)  //if unnamed reference
  105.         return MSG_UnnamedField;
  106.  
  107.       firstArg = "'" + escQuotes(fieldName) + "'";
  108.       secondArg = "'" + escQuotes(document.MM_IE_REFS[i]) + "'";
  109.       thirdArg = "'" + chkStr + "'"; //wrap in quotes
  110.       if (retArgs) retArgs += ","; //add comma if necessary
  111.       retArgs += firstArg + "," + secondArg + "," + thirdArg;
  112.     }
  113.   }
  114.   if (retArgs) return "MM_validateForm(" + retArgs + ")";  //return fn call with args
  115.   else return MSG_NoFieldsSet;
  116. }
  117.  
  118.  
  119.  
  120. //Returns a dummy function call to inform Dreamweaver the type of certain behavior
  121. //call arguments. This information is used by DW to fixup behavior args when the
  122. //document is moved or changed.
  123. //
  124. //It is passed an actual function call string generated by applyBehavior(), which
  125. //may have a variable list of arguments, and this should return a matching mask.
  126. //
  127. //The return values are:
  128. //  URL     : argument could be a file path, which DW will update during Save As...
  129. //  NS4.0ref: arg is an object ref that may be changed by Convert Tables to Layers
  130. //  IE4.0ref: arg is an object ref that may be changed by Convert Tables to Layers
  131. //  other...: argument is ignored
  132.  
  133. function identifyBehaviorArguments(fnCallStr) {
  134.   var argList, argArray, numArgGroups, i;
  135.  
  136.   argList = "";
  137.   argArray = extractArgs(fnCallStr);
  138.   numArgGroups = (argArray.length - 1) / 3; //args come in triplets
  139.   for (i=0; i<numArgGroups; i++) {          //with each NSobj,IEobj,test triplet
  140.     argList += ((argList)?",":"")+"NS4.0ref,IE4.0ref,other";
  141.   }
  142.   return argList;
  143. }
  144.  
  145.  
  146.  
  147. //Given the original function call, this parses out the args and updates
  148. //the UI.
  149.  
  150. function inspectBehavior(upStr){
  151.   var argArray,numArgs,found,i,numTokens,theFieldNS,theChk;
  152.  
  153.   argArray = extractArgs(upStr);  //get new list of Field,Chk pairs (ignore argArray[0])
  154.   numArgs = argArray.length;
  155.   for (i=1; i<(numArgs-2); i+=3) { //with each FieldNS, FieldIE, Chk triplet
  156.     theFieldNS = argArray[i];
  157.     theChk=argArray[i+2];
  158.  
  159.     //Now that form is there, look for field name
  160.     found = false;
  161.     numFields = document.MM_NS_REFS.length;
  162.     for (j=0; j<numFields; j++)  //check if Field is in menu
  163.       if (document.MM_NS_REFS[j] == theFieldNS) { //if Field there
  164.         addValueToMenuItem(document.theForm.fieldMenu,j,theChk);
  165.         found = true;
  166.         break;
  167.       }
  168.     if (!found) alert(errMsg(MSG_FldNotFound,theFieldNS,theChk)); //if Field name not found
  169.   }
  170.   document.theForm.fieldMenu.selectedIndex = 0;
  171.   displaySelection();
  172. }
  173.  
  174.  
  175.  
  176. //***************** LOCAL FUNCTIONS  ******************
  177.  
  178.  
  179. //Load the select menu with frame names.
  180.  
  181. function initializeUI(){
  182.   var niceNameSrcArray,nameArray,i;
  183.   var menuLength = 0; //menu now zero length
  184.  
  185.   //Populate the Form Menu
  186.   document.MM_NS_REFS = getAllObjectRefs("NS 4.0","INPUT/TEXT","TEXTAREA","INPUT/PASSWORD");
  187.   document.MM_IE_REFS = getAllObjectRefs("IE 4.0","INPUT/TEXT","TEXTAREA","INPUT/PASSWORD");
  188.   niceNameSrcArray = document.MM_NS_REFS;
  189.  
  190.   //Search for unreferenceable objects. <DIV id="foo"> is IE only, <LAYER> is NS only.
  191.   //if REF_CANNOT found, return empty string, and use IE refs for nice namelist.
  192.   for (i=0; i<document.MM_NS_REFS.length; i++) {
  193.     if (document.MM_IE_REFS[i].indexOf(REF_CANNOT) == 0) {
  194.       document.MM_IE_REFS[i] = ""; //blank it out
  195.     }
  196.     if (document.MM_NS_REFS[i].indexOf(REF_CANNOT) == 0) {
  197.       document.MM_NS_REFS[i] = ""; //blank it out
  198.       niceNameSrcArray = document.MM_IE_REFS; //use the IE list
  199.     }
  200.   }
  201.   nameArray = niceNames(niceNameSrcArray,TYPE_Text);
  202.  
  203.   for (i in nameArray) {
  204.     document.theForm.fieldMenu.options[i]=new Option(nameArray[i]); //load menu
  205.     menuLength++;
  206.   }
  207.  
  208.   //Store the field menu length
  209.   document.theForm.fieldMenu.length = menuLength;  //store the menu length (hack - prop not supp)
  210.  
  211.   //Select first item
  212.   document.theForm.fieldMenu.selectedIndex = 0;
  213. }
  214.  
  215.  
  216.  
  217. // Given an index into select "fieldMenu", returns any value in parens
  218.  
  219. function getMenuValue(menuIndex){
  220.   var checkStr,menuStr,startPos;
  221.  
  222.   checkStr = "";
  223.   menuStr = document.theForm.fieldMenu.options[menuIndex].text;
  224.   startPos = menuStr.indexOf("(");
  225.   if (startPos != -1)    //get previous check string
  226.     checkStr = menuStr.substring(startPos+1,menuStr.lastIndexOf(")"));
  227.   return checkStr;
  228. }
  229.  
  230.  
  231.  
  232. //Given a new text field has been selected in the menu,
  233. //loads the correct validation check settings into the checkboxes.
  234.  
  235. function displaySelection() {
  236.   var isReqd,theRadio,curFieldNum,menuStr,colonPos;
  237.  
  238.   isReqd = false;  //default settings
  239.   theRadio = 0;
  240.   curFieldNum = document.theForm.fieldMenu.selectedIndex; //get selected index
  241.   menuStr = getMenuValue(curFieldNum);  //get selection's value (in parens)
  242.   document.theForm.fromNum.value = "";
  243.   document.theForm.toNum.value = "";
  244.   if (menuStr) {
  245.     isReqd = (menuStr.charAt(0)=="R");  //true if R, false if N
  246.     if (menuStr.length > 1) {
  247.       if (menuStr.indexOf("isNum")!= -1) {theRadio = 1}
  248.       if (menuStr.indexOf("isEmail")!= -1) {theRadio = 2}
  249.       if (menuStr.indexOf("inRange")!= -1) {
  250.         theRadio = 3;
  251.         colonPos = menuStr.indexOf(':');
  252.         document.theForm.fromNum.value = menuStr.substring(8,colonPos);
  253.         document.theForm.toNum.value = menuStr.substring(colonPos+1,menuStr.length);
  254.       }
  255.     }
  256.   }
  257.   document.theForm.isReqd.checked = isReqd;  //check Required box
  258.   for (i=0; i<document.theForm.theCheck.length; i++)
  259.     document.theForm.theCheck[i].checked = (theRadio == i);
  260. }
  261.  
  262.  
  263.  
  264. //Given a selection change, gets the values from the checkboxes/radios etc.
  265. //and stores the checks in the menu next to the previous selected text field.
  266.  
  267. function saveCheckToMenu(newChk) {
  268.   var curFieldNum,isReqd,thingToAddToMenu;
  269.  
  270.   curFieldNum = document.theForm.fieldMenu.selectedIndex; //get index to swap
  271.   if (curFieldNum != null)  //if something selected
  272.     if (document.theForm.fieldMenu.options[curFieldNum].text) { //if there's a menu item
  273.       isReqd = (document.theForm.isReqd.checked)? "R" : "N";  //first char, R for required fld
  274.       if (newChk == "required") { //if they hit the "required" checkbox
  275.         newChk = getMenuValue(curFieldNum);
  276.         if (newChk) newChk = newChk.substring(1,newChk.length); //skip first char (R or N)
  277.       }
  278.       thingToAddToMenu = (isReqd == "N" && newChk == "")?"":isReqd+newChk; //concat R/N and check
  279.       addValueToMenuItem(document.theForm.fieldMenu, curFieldNum, thingToAddToMenu);
  280.       document.theForm.fieldMenu.selectedIndex = curFieldNum; //reset selection index
  281.     } else alert(MSG_NoSelection);
  282. }
  283.  
  284.  
  285.  
  286. //if the Range radio btn is not checked, do nothing
  287. //else if either entry is not a number, do nothing
  288. //else if a < b, construct range string
  289. //else give error
  290.  
  291. function saveRangeToMenu(newChk,fromRadio){
  292.   var fromNum,toNum,i,theRadio,rangeStr;
  293.  
  294.   if (document.theForm.theCheck[3].checked) { //if the radio is checked
  295.     fromNum = parseFloat(document.theForm.fromNum.value); //get from number
  296.     toNum = parseFloat(document.theForm.toNum.value); //get to number
  297.     if (!isNaN(fromNum) && !isNaN(toNum)) { //if valid numbers
  298.       if (fromNum < toNum) {
  299.         rangeStr = newChk + fromNum + ":" + toNum;
  300.         saveCheckToMenu(rangeStr);
  301.       } else {
  302.         saveCheckToMenu('');
  303.         if (fromRadio) alert(MSG_InvalidRange);
  304.       }
  305.     } else saveCheckToMenu('');
  306.   }
  307. }
  308.  
  309.  
  310.  
  311. //**************** GENERIC FUNCTIONS ****************
  312.  
  313. //function extractArgs(behFnCallStr){
  314. //function escQuotes(theStr){
  315. //function unescQuotes(theStr){
  316. //function stripValue(theStr) {
  317. //function addValueToMenuItem(theSelect,menuIndex,value) {
  318. //function niceNames(objRefArray,objTypeStr) {
  319. //function nameReduce (objName) {
  320. //function errMsg() {
  321.